<template>
  <div class="app-container">

    <el-form :inline="true" :model="replyPageRequest" class="demo-form-inline" size="small">
      <el-form-item :style="{maxWidth: isMobile ? '210px' : '500px'}">
        <el-input v-model="replyPageRequest.name" placeholder="请输入答辩名称">
          <el-button slot="append" type="primary" style="background-color: #409EFF; color: white" @click="getReplyList">
            搜索
          </el-button>
        </el-input>
      </el-form-item>
      <el-form-item style="position: absolute">
        <el-button type="success" @click="handleAddReply">
          创建答辩
        </el-button>
      </el-form-item>
    </el-form>

    <el-card v-for="reply in list" :key="reply.id" class="box-card">
      <router-link
        :to="{path: '/teacher/reply', query: {
          replyId: reply.id
      }}">
        <el-row :gutter="20">
          <el-col :span="17">
            <span style="font-size: larger">{{ reply.title }}</span>
          </el-col>
          <el-col :span="7"><span style="font-size: small">{{ reply.config }}</span></el-col>
        </el-row>
      </router-link>
    </el-card>

    <br>

    <div class="block">
      <el-pagination
        v-if="!isMobile"
        :current-page="page"
        :page-sizes="[5, 10, 15, 30, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="changSize"
        @current-change="changePage"/>
      <el-pagination
        v-else
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        small
        layout="prev, pager, next"
        @current-change="changePage"/>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="addReplyFlag"
      :width="isMobile ? '80%' : '50%'"
      title="创建答辩">
      <el-form ref="addReply1" :model="addReply" label-position="top">
        <el-row :gutter="5">
          <el-col :sm="12" :xs="24">
            <el-form-item
              :rules="[
                { required: true, message: '请输入答辩名称', trigger: 'blur' }
              ]"
              prop="title"
              label="答辩名称">
              <el-input v-model="addReply.title" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :xs="24">
            <el-form-item
              :rules="[
                {required: true, message: '请选择答辩教师小组', trigger: 'change'}
              ]"
              prop="groupId"
              label="教师小组">
              <el-select v-model="addReply.groupId" placeholder="请选择教师小组" style="width: 100%;">
                <el-option
                  v-for="group in teacherGroupList"
                  :label="group.name"
                  :key="group.id"
                  :value="group.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item
              :rules="[
                { type: 'date', required: true, message: '请选择开始日期', trigger: 'change' }
              ]"
              prop="startTime"
              label="答辩开始日期">
              <el-date-picker
                v-model="addReply.startTime"
                :picker-options="pickerOptionsStart"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[
                { type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }
              ]"
              prop="endTime"
              label="答辩结束日期">
              <el-date-picker
                v-model="addReply.endTime"
                :picker-options="pickerOptionsEnd"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="addReply2" :model="addReply">
        <el-row :gutter="5">
          <el-col :sm="12" :xs="24">
            <el-form-item label="学生匿名打分权重">
              <el-input-number
                v-model="addReply.weight"
                :min="0"
                :max="100"
                :style="{width: isMobile ? '50%' : '80%'}"
                controls-position="right"
                label="学生匿名打分权重"/>
            </el-form-item>
          </el-col>
          <el-col :sm="5" :xs="11">
            <el-form-item label="学生自评">
              <el-tooltip :content="(addReply.selfMark === '0' ? '已关闭' : '已开启') + '学生自评'" placement="top">
                <el-switch v-model="addReply.selfMark" active-value="1" inactive-value="0"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :sm="5" :xs="13">
            <el-form-item label="成绩分析">
              <el-tooltip :content="(addReply.visible === '0' ? '已关闭' : '已开启') + '成绩分析'" placement="top">
                <el-switch v-model="addReply.visible" active-value="1" inactive-value="0"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="addReply3" :model="addReply" label-position="top">
        <el-row :gutter="5">
          <el-col :sm="12" :xs="24">
            <el-form-item
              :rules="[
                { required: false },
                { validator: numberRule, message: '请在两个人员库中至少选一答辩成员', trigger: 'change' }
              ]"
              prop="clazzIds"
              label="从班级库选择答辩人员">
              <el-select
                v-model="addReply.clazzIds"
                multiple
                collapse-tags
                filterable
                placeholder="请选择答辩班级"
                style="width: 100%;">
                <el-option
                  v-for="clazz in clazzList"
                  :label="clazz.name"
                  :key="clazz.id"
                  :value="clazz.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :xs="24">
            <el-form-item
              :rules="[
                { required: false },
                { validator: numberRule, message: '请在两个人员库中至少选一答辩成员', trigger: 'change' }
              ]"
              prop="studentIds"
              label="从学生库选择答辩人员">
              <el-select
                v-model="addReply.studentIds"
                multiple
                collapse-tags
                filterable
                placeholder="请选择答辩人员"
                style="width: 100%;">
                <el-option
                  v-for="student in studentList"
                  :label="student.name"
                  :key="student.id"
                  :value="student.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider/>
      <p style="font-size: small; color: red">注：学生打分权重0为不开启学生打分<strong>（包括学生自评）</strong>，重复答辩人员只会添加一次，答辩人员不能为空</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddReply('addReply')">创 建</el-button>
        <el-button @click="addReplyFlag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import teacherReplyApi from '@/api/teacher/reply'
import { isPasswordValid } from '@/api/login'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      page: 1,
      total: 0,
      pageSize: 10,
      LabelWidth: '80px',
      isMobile: false,

      replyPageRequest: {
        page: 1,
        limit: 10,
        name: null
      },

      teacherGroupList: [],
      clazzList: [],
      studentList: [],

      addReplyFlag: false,
      flag: false,
      addReply: {
        title: null,
        groupId: null,
        startTime: null,
        endTime: null,
        weight: 0,
        selfMark: 0,
        visible: 0,
        clazzIds: null,
        studentIds: null
      },
      pickerOptionsStart: {
        disabledDate: time => {
          const endDateVal = this.addReply.endTime
          if (endDateVal) {
            return time.getTime() > new Date(endDateVal).getTime()
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          const beginDateVal = this.addReply.startTime
          if (beginDateVal) {
            return (
              time.getTime() < new Date(beginDateVal).getTime()
            )
          }
        }
      }
    }
  },
  created() {
    this.isMobile = document.body.clientWidth <= 576
    this.getReplyList()
    this.isPasswordValid()
  },
  methods: {
    getReplyList() {
      this.listLoading = true
      this.replyPageRequest.page = this.page
      this.replyPageRequest.limit = this.pageSize
      teacherReplyApi.getAllReplys(this.replyPageRequest).then(res => {
        this.listLoading = false
        this.total = Number.parseInt(res.result.counts)
        this.list = res.result.items
      }).catch(error => {
        console.log(error)
      })
    },
    isPasswordValid() {
      isPasswordValid().then(res => {
        if (res.result) {
          this.instance = this.$notify({
            title: '密码检验',
            dangerouslyUseHTMLString: true,
            message: '您的密码为初始密码，为了您的账号安全，请尽快修改新的密码，点击<a href="#/teacher/info" class="" style="color: rgb(64, 158, 255);"> 修改密码 </a>，或在“个人信息”中查看修改。',
            duration: 0,
            onClick: () => {
              if (event.target.nodeName === 'A') {
                this.instance.close()
              }
            }
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    changSize(pageSize) {
      this.pageSize = pageSize
      this.getReplyList()
    },
    changePage(page) {
      this.page = page
      this.getReplyList()
    },
    handleAddReply() {
      this.getTeacherGroupList()
      this.getClazzList()
      this.getStudentList()
      this.addReplyFlag = true
    },
    getTeacherGroupList() {
      if (this.teacherGroupList.length === 0) {
        teacherReplyApi.getAllGroups().then(res => {
          this.teacherGroupList = res.result
        }).catch(error => {
          console.log(error)
        })
      }
    },
    getClazzList() {
      if (this.clazzList.length === 0) {
        teacherReplyApi.getAllClass().then(res => {
          this.clazzList = res.result
        }).catch(error => {
          console.log(error)
        })
      }
    },
    getStudentList() {
      if (this.studentList.length === 0) {
        teacherReplyApi.getAllStudents().then(res => {
          this.studentList = res.result
        }).catch(error => {
          console.log(error)
        })
      }
    },
    numberRule(rule, value, callback) {
      if (this.flag && this.addReply.clazzIds.length === 0 && this.addReply.studentIds.length === 0) {
        return callback(new Error('请在两个人员库中至少选一答辩成员'))
      }
      return callback()
    },
    submitAddReply(formName) {
      this.flag = true
      const p1 = new Promise((resolve, reject) => {
        this.$refs[formName + '1'].validate(valid => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })

      const p2 = new Promise((resolve, reject) => {
        this.$refs[formName + '3'].validate(valid => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })

      Promise.all([p1, p2]).then(() => {
        this.addReply.endTime = new Date(this.addReply.endTime.getTime() + (24 * 60 * 60 - 1) * 1000)
        teacherReplyApi.addReply(this.addReply).then(res => {
          this.$message({
            message: '创建成功',
            type: 'success'
          })
          this.addReplyFlag = false
          this.getReplyList()
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          message: '请按规则完善信息',
          type: 'warning'
        })
      })
    }
  }
}

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.box-card:hover {
  color: rgb(64, 158, 255);
}
</style>
